#!/bin/bash

BASE_PATH="$HOME/.docker"
NETWORK_NAME="mara-network"

SERVICE_NAME="mara-mock-server"
SERVICE_VERSION="2.0.0-SNAPSHOT"
DEFAULT_PORT="3000"
BUILD_DATE=`date -u +'%Y-%m-%dT%H:%M:%SZ'`p

MOCK_PATH=$MOCK_PATH
if [ -z $MOCK_PATH ]; then
  MOCK_PATH="$PWD/mock"
fi

# registry path
REGISTRY="svr01:5000"

mprint() {
  echo -e $(TZ=UTC-8 date +'%Y-%m-%dT%H:%M:%SZ') $*
}

clean_up() {
  mprint "clean up"
  if [[ $(docker images -q -f dangling=true | wc -l) -gt 0 ]]; then
    docker rmi $(docker images -q -f dangling=true)
  fi
}

build_repo() {
  mprint "build $1"
  docker build . --tag=$REGISTRY/$SERVICE_NAME:$SERVICE_VERSION \
    --build-arg BUILD_ENV=$1
  stop_repo
  clean_up
}

build_multi_repo() {
  docker buildx \
    build --platform=linux/arm64,linux/amd64 \
    --tag=$REGISTRY/$SERVICE_NAME:$SERVICE_VERSION \
    --push .
  # stop_repo
  # clean_up
}

clean_repo() {
  stop_repo
  if [ ! -z `docker images -q $REGISTRY/$SERVICE_NAME:$SERVICE_VERSION` ]; then
    docker rmi $REGISTRY/$SERVICE_NAME:$SERVICE_VERSION
  fi
}

push_repo() {
  docker push $REGISTRY/$SERVICE_NAME:$SERVICE_VERSION
}

stop_repo() {
  for id in `docker ps -q -a --filter name=$SERVICE_NAME`; do
    docker rm -f $id
  done
}

start_repo() {
  PORT=$DEFAULT_PORT
  [ $1 ] && PORT=$1

  docker run -d \
    -p $PORT:$PORT \
    --restart=on-failure:5 \
    --name $SERVICE_NAME \
    --network $NETWORK_NAME \
    -v $MOCK_PATH:/app/mock \
    $REGISTRY/$SERVICE_NAME:$SERVICE_VERSION
}

upgrade_repo() {
  stop_repo
  clean_repo
  start_repo
}

######################
#
# main process
#
######################

usage() {
  echo "
Usage: $CMD COMMAND ...

Devops control commands.

Commands:
  build          build Docker Images from sources.
  clean          remove Docker Images in local.
  push           push Docker Images to Registry.
  start          start Docker Containers.
  stop           stop Docker Containers.

Run '$CMD COMMAND --help' for more information on a command.
"
}

CMD=$0

if [ $# == 0 ]; then
  usage
  exit 0
fi

case "$1" in
build)
  shift
  build_repo $@
  ;;
build-multi)
  shift
  build_multi_repo
  ;;  
clean)
  shift
  clean_repo
  ;;  
push)
  shift
  push_repo
  ;;
start)
  shift
  start_repo $@
  ;;
stop)
  shift
  stop_repo
  ;;
upgrade)
  shift
  upgrade_repo
  ;;    
*)
  echo "invalid command $1"
  usage
  exit -1
  ;;
esac
